<?php

namespace addons\mental\controller;

use addons\mental\model\Order as orderModel;
use app\admin\model\Exchangecode;
use app\admin\model\video\VideoCollect;
use app\admin\model\video\Order;
use app\admin\model\video\Video as VideoModel;
use think\Db;
use think\Exception;

class Video extends Base
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['list','category_list','detail'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    private $model = null;
    private $videoCollectModel = null;
    private $videoCategoryModel = null;
    private $videoCatalogueModel = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\video\Video();
        $this->videoCollectModel = new \app\admin\model\video\VideoCollect();
        $this->videoCategoryModel = new \app\admin\model\video\Category();
        $this->videoCatalogueModel = new \app\admin\model\video\Catalogue();

    }
    /**
     * 视频目录列表
     */
    public function cataloguelist()
    {
        $pagesize = $this->request->param('pagesize', 10);
        $keywords = $this->request->param('keywords', '');
        $type = $this->request->param('type', 0);//1在线调适 2专家讲座
        $where = [];
        $where['is_del'] = ['=',0];
        $where['type'] = ['=',$type];
        if ($keywords){
            $where['title'] = ['like', '%' . $keywords . '%'];
        }
//        if ($type){
//            $where['type'] = ['=',$type];
//        }

        $list = $this->model
            ->where($where)
            ->paginate($pagesize);
        if ($list){
            foreach ($list as $key=>&$value){
                if ($this->auth->id){
                    $like = $this->videoCollectModel->where(['user_id'=>$this->auth->id,'main_id'=>$value['id']])->find();
                    $value['like'] = $like?1:0;
                }else{
                    $value['like'] = 0;
                }

            }
        }
        $this->success('成功', $list);
    }

    /**
     * 视频列表
     */
    public function list()
    {
        $pagesize = $this->request->param('pagesize', 10);
        $keywords = $this->request->param('keywords', '');
        $category_id = $this->request->param('category_id', 0);
        $where = [];
        $where['video.is_del'] = ['=',0];
        if ($keywords){
            $where['title'] = ['like', '%' . $keywords . '%'];
        }
        if ($category_id){
            $where['video_category_id'] = ['=',$category_id];
        }

        $list = $this->model
            ->with(['videocategory'])
            ->where($where)
            ->paginate($pagesize);
        if ($list){
            foreach ($list as $key=>&$value){
                if ($this->auth->id){
                    $like = $this->videoCollectModel->where(['user_id'=>$this->auth->id,'main_id'=>$value['id']])->find();
                    $value['like'] = $like?1:0;
                }else{
                    $value['like'] = 0;
                }

            }
        }
        $this->success('成功', $list);
    }

    /*
     * 视频详情
     * */
    public function detail()
    {
        $id = $this->request->param('id', 0);
        $data = $this->model->with(['videocategory'])->where(['video.id'=>$id])->find();
        if (!$data){
            $this->error('视频不存在');
        }
        //验证用户是否购买
        if ($data['price']>0){
            $videoOrderModel = new Order();
            $has_paid = $videoOrderModel->where(['video_id'=>$id,'user_id'=>$this->auth->id,'status'=>'paid'])->find();
            if (!$has_paid){
                $this->error('还未购买');
            }
        }
        $like = $this->videoCollectModel->where(['user_id'=>$this->auth->id,'main_id'=>$id])->find();
        $data['like'] = $like?1:0;
        $data['catalogue'] = $this->videoCatalogueModel->where(['video_id'=>$id])->order('sort','asc')->select();
        $this->success('成功', $data);
    }

    /*
     * 视频分类
     * */
    public function category_list()
    {
        $list = $this->videoCategoryModel->where(['is_del'=>0])->select();
        $this->success('成功', $list);
    }

    /*
     * 视频收藏
     * */
    public function collect()
    {
        $id = $this->request->param('id', 0);
        $like = $this->videoCollectModel->where(['user_id'=>$this->auth->id,'main_id'=>$id])->find();
        if ($like){
            $like->delete();
        }else{
            $this->videoCollectModel->save(['user_id'=>$this->auth->id,'main_id'=>$id]);
        }
        $this->success('成功', '');
    }

    /*
     * 视频收藏列表
     * */
    public function collect_list()
    {
        $pagesize = $this->request->param('pagesize', 10);
        $list = VideoCollect::with(['video'])
            ->where(['user_id'=>$this->auth->id])
            ->order('id','desc')
            ->paginate($pagesize);
        if ($list){
            foreach ($list as $key=>&$value){
                $value['like_num'] = $this->videoCollectModel->where(['main_id'=>$value['main_id']])->count();;
            }
        }
        $this->success('成功', $list);
    }

    /*
     * 视频订单列表
     * */
    public function order_list()
    {
        $pagesize = $this->request->param('pagesize', 10);
        $videoOrderModel = new Order();
        $list = $videoOrderModel->with(['video'])
            ->where(['user_id'=>$this->auth->id,'status'=>'paid'])
            ->order('id','desc')
            ->paginate($pagesize);

        $this->success('成功', $list);
    }

    /*
     * 创建视频订单
     * */
    public function create_order()
    {
        $video_id = $this->request->param('video_id', 0);


        $user_id = $this->auth->id;
        $video = VideoModel::where(['id'=>$video_id])->find();
        if (!$video){
            $this->error('视频不存在');
        }
        $videoOrderModel = new Order();
        $has_order = $videoOrderModel->where(['video_id'=>$video_id,'user_id'=>$user_id,'status'=>'paid'])->find();
        if ($has_order){
            $this->error('您已购买过');
        }

        $order_id = date("Ymdhis") . sprintf("%08d", $user_id) . mt_rand(1000, 9999);

        // 启动事务
        Db::startTrans();
        try{
            //创建订单
            $order = $videoOrderModel->create([
                'order_id'=>$order_id,
                'video_id'=>$video_id,
                'user_id'=>$user_id,
                'amount'=>$video['price'],
                'payamount'=>$video['price'],
                'createtime'=>time(),
            ]);

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error('下单失败:'.$e->getMessage());
        }

        $this->success('下单成功',$order);
    }

    /*
     * 订单支付
     * */
    public function pay()
    {
        $order_id = $this->request->param('order_id', 0);
        $paytype = $this->request->param('paytype', 'wechat');
        $code = $this->request->param('code', '');

        $user_id = $this->auth->id;
//        var_dump($order_id);
//        var_dump($code);
//        halt($user_id);
        $videoOrderModel = new Order();
        $order = $videoOrderModel->where(['order_id'=>$order_id,'user_id'=>$user_id,'status'=>'created'])->find();
        if (!$order){
            $this->error('订单不存在');
        }

        if ($paytype=='code'){
            if (!$code){
                $this->error('请输入兑换码');
            }
            $code_exist = Exchangecode::where(['code'=>$code,'status'=>0,'type'=>4])->find();
            if (!$code_exist){
                $this->error('兑换码不存在');
            }
            //更新兑换卡
            $code_exist->sp_videoid = $order['video_id'];
            $code_exist->user_id = $user_id;
            $code_exist->order_id = $order_id;
            $code_exist->status = 1;
            $code_exist->save();

            //更新订单
            $order->status = 'paid';
            $order->paytime = time();
            $order->paytype = 'code';
            $order->save();
        }else{
            try {

                $paytype = 'wechat';
                $method = 'miniapp';
                $attach = 'video';//订单类型 mental=评测 video=视频 consult=沟通
                $url = $this->request->param('url', '', 'trim'); //公众号授权回调url 或 h5支付回调url
                $openid = \app\admin\model\User::where(['id'=>$this->auth->id])->value('openid');

                $result = orderModel::pay($this->auth->id, $order_id, $order->amount, $paytype, $method, $url, $openid, $attach);
                if (!is_array($result)) {
                    $this->success(__('Operation completed'), $result);
                } else {
                    $this->error(__('Operation failed'), $result['data'], 2); //判断公众号授权
                }
            } catch (Exception $e) {
                $this->error($e->getMessage());
            }
        }



        $this->success('发起支付');
    }

}
